package com.tanhua.app.Service;

import cn.hutool.crypto.SecureUtil;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.config.template.HuanXinTemplate;
import com.tanhua.config.template.SmsTemplate;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.pojo.User;
import com.tanhua.model.pojo.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.FansVo;
import com.tanhua.model.vo.LikeCountVo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class UserService {
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @DubboReference
    private UserApi userApi;
    @DubboReference
    private UserLikeApi userLikeApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private RecommendUserApi recommendUserApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private UserFreezeService userFreezeService;
    @Autowired
    private MqMessageService mqMessageService;
    @Autowired
    private MessagesService messagesService;

    //    登录---获取验证码
    public void sendCode(String phone) {
        User user = userApi.findByMobile(phone);
        if (user != null) {
            userFreezeService.checkUserFreeze(user.getId(), "1");
        }

//        String code = RandomStringUtils.randomNumeric(6);
//        smsTemplate.sendSms(phone,code);
        String code = "123456";
        stringRedisTemplate.opsForValue().set(Constants.SMS_CODE + phone, code, 5, TimeUnit.MINUTES);
    }

    //    登录---验证码校验
    public Map<String, Object> loginVerification(String mobile, String verificationCode) {
        String code = stringRedisTemplate.opsForValue().get(Constants.SMS_CODE + mobile);
        if (StringUtils.isEmpty(code) || !code.equals(verificationCode)) {
            throw new BusinessException(ErrorResult.loginError());
        }
        boolean isNew = false;
        User user = userApi.findByMobile(mobile);
        String type = "0101";
        if (user == null) {
            type = "0102";
            user = new User();
            user.setMobile(mobile);
            user.setPassword(SecureUtil.md5("123456"));
            Long id = userApi.save(user);
            user.setId(id);
            isNew = true;

            String hxUser = Constants.HX_USER_PREFIX + id;
            Boolean create = huanXinTemplate.createUser(hxUser, user.getPassword());
            if (create) {
                user.setHxUser(Constants.HX_USER_PREFIX + id);
                user.setHxPassword("123456");
                userApi.update(user);
            }
        }

        HashMap<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", mobile);
        String token = JwtUtils.getToken(tokenMap);
        HashMap<String, Object> retmap = new HashMap<>();
        retmap.put("token", token);
        retmap.put("isNew", isNew);

        mqMessageService.sendLogMessage(user.getId(), type, "user", "");
        return retmap;
    }

    //    修改手机号 - 2 校验验证码
    public boolean checkVerification(String mobile, String verificationCode) {
        String code = stringRedisTemplate.opsForValue().get(Constants.SMS_CODE + mobile);
        if (StringUtils.isEmpty(code) || !code.equals(verificationCode)) {
            throw new BusinessException(ErrorResult.loginError());
        }
        return true;
    }

    //    修改手机号 = 3 保存
    public void phone(String phone) {
        User user = userApi.findByMobile(phone);
        if (user != null) {
            throw new BusinessException(ErrorResult.mobileError());
        }
        user = new User();
        user.setMobile(phone);
        user.setId(UserHolder.getUserId());
        userApi.update(user);
    }

    //    互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
    public PageResult fansList(Integer page, Integer pagesize, String type, String nickname) {
        List<Long> ids = new ArrayList<>();
        PageResult<UserLike> pages = new PageResult<>();
        Long userId = UserHolder.getUserId();
        Boolean alreadyLove = false;
        switch (type) {
            case "1":
                pages = userLikeApi.together(page, pagesize, userId);
                ids = pages.getItems().stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
                alreadyLove = true;
                break;
            case "2":
                pages = userLikeApi.findLikes(page, pagesize,userId);
                ids = pages.getItems().stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
                break;
            case "3":
                pages = userLikeApi.findFans(page, pagesize,userId);
                ids = pages.getItems().stream().map(UserLike::getUserId).collect(Collectors.toList());
                break;
        }
        List<UserInfo> userInfos = userInfoApi.findByNicknameIds(ids,nickname);
        List<FansVo> vos = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            RecommendUser recommendUser = recommendUserApi.queryByUserId(userId, userInfo.getId());
            FansVo vo = FansVo.init(userInfo, recommendUser.getScore(), alreadyLove);
            vos.add(vo);
        }
        return new PageResult(page,pagesize,pages.getCounts(),vos);
    }

    //    互相喜欢，喜欢，粉丝 - 统计
    public LikeCountVo likeCounts() {
        return userLikeApi.findCount(UserHolder.getUserId());
    }

    //    喜欢 - 取消
    public void deleteLike(String likeId) {
        Long userId = UserHolder.getUserId();
        Boolean aBoolean = userLikeApi.saveOrUpdate(Long.parseLong(likeId),userId , false);
        if (!aBoolean) {
            messagesService.removeContacts(Long.parseLong(likeId));
            Boolean aBoolean1 = huanXinTemplate.deleteContact(likeId, userId.toString());
        }
    }

    //    粉丝 - 喜欢
    public void fansLike(String likeId) {
        Long userId = UserHolder.getUserId();
        Boolean aBoolean = userLikeApi.saveOrUpdate(Long.parseLong(likeId), userId, true);
        if (aBoolean) {
            messagesService.contacts(Long.parseLong(likeId));
            Boolean aBoolean1 = huanXinTemplate.addContact(likeId, userId.toString());
        }
    }

}
